<template>
  <div class="container">
    <div class="main">
      <!-- 表格头部操作按钮和筛选条件 -->
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
      </div>
      <!-- 表格展示订单列表 -->
      <el-table :data="filteredTableData" border class="eltable" style="overflow: auto;">
        <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
        <el-table-column fixed label="订单状态" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scdd_zt] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column fixed label="优先级" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scdd_yxj] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column  prop="scdd_jd" label="订单进度" width="85">
          <template #default="{ row }">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${row.scdd_jd}%` }">
                {{ row.scdd_jd }}%
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- 其他表格列 -->
        <el-table-column fixed prop="scdd_code" label="订单编码" width="165"></el-table-column>
        <el-table-column label="订单类型" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scdd_lx] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="订单性质" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scdd_xz] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="ks_code" label="客户编码" width="180"></el-table-column>
        <el-table-column prop="ks_name" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="ht_code" label="合同编码" width="180"></el-table-column>
        <el-table-column prop="scdd_sl" label="订单数量" width="180"></el-table-column>
        <el-table-column prop="scdd_wcsl" label="完成数量" width="180"></el-table-column>
        <el-table-column :label="`交货日期`" width="180">
          <template #default="{ row }">
            {{ formatDate(row.delivery_date) }}
          </template>
        </el-table-column>
        <el-table-column label="计划开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.planned_start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="planned_completion_time" label="计划完成时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.planned_completion_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_by" label="创建人" width="180"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="350">
          <template #default="{ row }">
            <el-button type="text" @click="Details(row)">详情</el-button>
            <el-button type="text" @click="Issue(row)">下发</el-button>
            <el-button type="text" @click="Withdraw(row)">撤回</el-button>
            <el-button type="text" @click="End(row)">终止</el-button>
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="dialogVisible" custom-class="order-dialog"
      style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <!-- 订单基本信息 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产订单号">
              {{ formData.scdd_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级">
              {{ dictionaryNames[formData.scdd_yxj] || '未知' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单类型">
              {{ dictionaryNames[formData.scdd_lx] || '未知' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单性质">
              {{ dictionaryNames[formData.scdd_xz] || '未知' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              {{ formData.ks_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编码">
              {{ formData.ht_code }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交货时间">
              {{ formatDate(formData.delivery_date) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单开始时间">
              {{ formatDate(formData.planned_start_time) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单结束时间">
              {{ formatDate(formData.planned_completion_time) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务数量">
              {{ formData.scdd_sl }}
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              {{ formData.seddbz }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="完成数量">
              {{ formData.scdd_wcsl }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单进度">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: `${formData.scdd_jd}%` }">
                  {{ formData.scdd_jd }}%
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p class="product-title">产品详情：</p>
      <!-- 产品详情表格，只有对话框显示时才渲染 -->
      <el-table v-if="dialogVisible" :data="productDetailsData" border class="product-table">
        <el-table-column prop="id" label="序号" width="80"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称"></el-table-column>
        <el-table-column prop="cp_xh" label="产品型号"></el-table-column>
        <el-table-column prop="cp_shu" label="产品数量" width="120"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="Mtkname" v-model="dialogVisibles" custom-class="plan-dialog"
      style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产订单编码:">
              <el-input v-model="formData.scdd_code" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单优先级:" prop="scdd_yxj">
              <el-select v-model="formData.scdd_yxj" placeholder="请选择">
                <el-option v-for="item in priorityOptions" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单类型:" prop="scdd_lx">
              <el-select v-model="formData.scdd_lx" placeholder="请选择">
                <el-option v-for="item in orderTypeOptions" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单性质:" prop="scdd_xz">
              <el-select v-model="formData.scdd_xz" placeholder="请选择">
                <el-option v-for="item in ddsz" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编码:" prop="ks_name">
              <el-input v-model="formData.ks_name" placeholder="请输入客户编码" @click="toggleKsMTK"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编码:">
              <el-input v-model="formData.ht_code" readonly placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码:" prop="cp_code">
              <el-input v-model="cp_code" placeholder="请输入产品名称" @click="toggleCPMTK"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单数量:">
              <el-input v-model="formData.scdd_sl" placeholder="请输入订单数量" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col>
          <el-col :span="24">
            <el-form-item label="交货日期:" prop="delivery_date">
              <el-date-picker v-model="formData.delivery_date" type="date" placeholder="请选择交货日期" :size="size"
                value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-col>
        <el-row>
          <el-col :span="24">
            <el-form-item label="开始时间:" prop="planned_start_time">
              <el-date-picker v-model="formData.planned_start_time" type="date" 
                placeholder="请选择订单开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="完成时间:" prop="planned_completion_time">
              <el-date-picker v-model="formData.planned_completion_time" type="date"
                placeholder="请选择订单完成时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:">
          <el-input type="textarea" v-model="formData.seddbz" placeholder="请输入备注"></el-input>
        </el-form-item>
        <p>产品详情：</p>
        <!-- 产品详情表格，只有对话框显示时才渲染 -->
        <el-table v-if="dialogVisibles" :data="productDetailsData" border class="eltable">
          <el-table-column prop="cp_code" label="产品编码"></el-table-column>
          <el-table-column prop="cp_name" label="产品名称"></el-table-column>
          <el-table-column prop="cp_xh" label="产品型号"></el-table-column>
          <el-table-column prop="cp_shu" label="产品数量" width="120">
            <template v-slot="{ row }">
              <el-input v-model="row.cp_shu" placeholder="请输入数量" @input="handleInputChange(row)" />
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog v-model="isCPMTKVisible" title="选择产品"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <CPMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection"></CPMTK>
    </el-dialog>

    <el-dialog v-model="isKsMTKVisible" title="选择客商"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <KsMTK @selection-confirmed="handleSelectionConfirmeds" @cancel-selection="handleCancelSelections"></KsMTK>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watchEffect, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import CPMTK from '../MTK/CPMTK.vue';
import KsMTK from '../MTK/KsMTK.vue';

// 封装请求函数
const request = async (url, options = {}) => {
  try {
    const response = await axios({ url, ...options });
    return response.data;
  } catch (error) {
    console.error(`请求 ${url} 失败:`, error);
    ElMessage.error(`请求失败: ${error.message}`);
    throw error;
  }
};

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
};

// 过滤数据函数
const filterTableData = (tableData, currentPage, pageSize) => {
  const start = (currentPage - 1) * pageSize;
  return tableData.slice(start, start + pageSize);
};

// 获取字典名称函数
const getDictionaryName = async (dictionaryId, dictionaryNames, request) => {
  if (!dictionaryId) return '';
  if (dictionaryNames.value[dictionaryId]) {
    return dictionaryNames.value[dictionaryId];
  }
  try {
    const data = await request(`/api/Dict/GetName?dictionary_id=${dictionaryId}`);
    dictionaryNames.value[dictionaryId] = data;
    return data;
  } catch (error) {
    console.error(`Error fetching dictionary name: ${error.message}`);
    return '';
  }
};

// 构造 AddMbd_gx 请求参数的函数
export default {
  components: { CPMTK, KsMTK },
  setup() {
    const tableData = ref([]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const dictionaryNames = ref({}); // 存储字典名称
    const dialogVisible = ref(false);  //isKsMTKVisible
    const dialogVisibles = ref(false);
    const isCPMTKVisible = ref(false);
    const isKsMTKVisible = ref(false);
    const formData = ref({
      scdd_code: '',
      scdd_yxj: null,
      scdd_lx: null,
      scdd_xz: null,
      ks_code: '',
      ht_code: '',
      scdd_sl: 0,
      delivery_date: null,
      planned_start_time: null,
      planned_completion_time: null,
      seddbz: '',
      create_by: sessionStorage.getItem('u')
    });
    const CPdataTemplate = ref({
      id: 0,
      scdd_code: '',
      cp_code: '',
      cp_name: '',
      cp_xh: '',
      cp_lx: 0,
      cp_fl: 0,
      pp_code: '',
      dw_code: '',
      dw_name: '',
      bom_code: '',
      cp_shu: 0,
    });
    const CPdataArray = ref([]);
    const productDetailsData = ref([]);
    const formRef = ref(null); // 表单引用
    const Mtkname = ref();
    const priorityOptions = ref({}); //订单优先级
    const orderTypeOptions = ref({}); //订单类型  
    const ddsz = ref({}); //订单性质
    const cp_code = ref([]);
    // 获取表格数据
    const fetchData = async () => {
      try {
        const data = await request('/api/Mes_SCDD/GetMes_SCDD');
        tableData.value = data;
        totalItems.value = data.length;
        const res = await request('/api/Dict/GetOneDict?id=12')
        orderTypeOptions.value = res;
        const ress = await request('/api/Dict/GetOneDict?id=14')
        priorityOptions.value = ress;
        const resss = await request('/api/Dict/GetOneDict?id=13')
        ddsz.value = resss;
      } catch (error) {
        console.error('Error fetching tableData:', error);
      }
    };
    // 计算过滤后的表格数据
    const filteredTableData = computed(() => {
      return filterTableData(tableData.value, currentPage.value, pageSize.value);
    });
    // 表单验证规则
    const formRules = ref({
      scdd_yxj: [
        { required: true, message: '请选择订单优先级', trigger: 'change' }
      ],
      scdd_lx: [
        { required: true, message: '请选择订单类型', trigger: 'change' }
      ],
      scdd_xz: [
        { required: true, message: '请选择订单性质', trigger: 'change' }
      ],
      ks_code: [
        { required: true, message: '请输入客户编码', trigger: 'blur' }
      ],
      // cp_code: [
      //   { required: true, message: '请输入产品编码', trigger: 'blur' }
      // ],
      delivery_date: [
        { required: true, message: '请选择交货日期', trigger: 'change' }
      ],
      planned_start_time: [
        { required: true, message: '请选择订单开始时间', trigger: 'change' }
      ],
      planned_completion_time: [
        { required: true, message: '请选择订单完成时间', trigger: 'change' }
      ],
      seddbz: [
        { required: true, message: '请输入备注', trigger: 'blur' }
      ]
    });
    //终止
    const End = async (row) => {
      try {
        // 获取订单状态  
        const state = await request(`/api/Mes_scjh/GetStatus?scdd_code=${row.scdd_code}`);
        // 判断状态数组中是否有值等于 55  
        const hasValue55 = state.includes(55);

        if (hasValue55) {
          ElMessage.error('订单已分解不可操作');
          return;
        }
        ElMessageBox.confirm('确定终止吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // 更新订单状态的 URL  
            const url = `/api/Mes_SCDD/UpdateStatus?code=${row.scdd_code}&state=51&update_by=${sessionStorage.getItem('u')}`;
            // 终止生产计划的 URL  
            const deleteUrl = `/api/Mes_scjh/UpdateStatus?scdd_code=${row.scdd_code}&state=51&update_by=${sessionStorage.getItem('u')}&scjh_code="1"`;
            // 使用 Promise.all 确保两个请求都成功  
            Promise.all([
              axios.put(url, {}),
              axios.put(deleteUrl, {})
            ]);
            // 两个请求都成功后提示  
            ElMessage.success('已终止该生产订单以及它的生产计划!');

            // 刷新数据  
            fetchData();
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消终止'
            });
          });
      } catch (error) {
        // 错误处理  
        ElMessage.error('操作失败: ' + error.message);
      }
    }
    //撤回
    const Withdraw = async (row) => {
      // 获取订单状态  
      const state = await request(`/api/Mes_scjh/GetStatus?scdd_code=${row.scdd_code}`);
      // 循环判断 state 数组中是否有值等于 55  
      let hasValue55 = false;
      for (let i = 0; i < state.length; i++) {
        if (state[i] === 55) {
          hasValue55 = true;
          break;
        }
      }
      // 如果状态中包含 55，显示错误消息  
      if (hasValue55) {
        ElMessage.error('该订单的生产计划已经分解不可操作');
        return;
      }
      ElMessageBox.confirm('确定撤回吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 更新订单状态  
          const url = `/api/Mes_SCDD/UpdateStatus?code=${row.scdd_code}&state=50&update_by=${sessionStorage.getItem('u')}`;
          try {
            axios.put(url, {});
            // 删除生产计划  
            const deleteUrl = `/api/Mes_scjh/DeleteScjh?scdd_code=${row.scdd_code}`;
            axios.delete(deleteUrl);
            ElMessage.success('撤回该生产订单!');
            fetchData();
          } catch (error) {
            ElMessage.error('操作失败: ' + error.message);
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消撤回'
          });
        });
    }
    // 保存表单
    const saveForm = async () => {
      await formRef.value.validate((valid) => {
        if (valid) {
          if (formData.value.scdd_id) {
            // 修改操作
            axios.put('/api/Mes_SCDD/UpdateMes_SCDD', formData.value)
              .then(response => {
                productDetailsData.value.forEach(product => {
                  const cpItem = { ...CPdataTemplate.value };
                  cpItem.id = 0;
                  cpItem.scdd_code = formData.value.scdd_code;
                  cpItem.cp_code = product.cp_code;
                  cpItem.cp_name = product.cp_name;
                  cpItem.cp_xh = product.cp_xh;
                  cpItem.cp_lx = product.cp_lx;
                  cpItem.cp_fl = product.cp_fl;
                  cpItem.pp_code = product.pp_code;
                  cpItem.dw_code = product.dw_code;
                  cpItem.dw_name = product.dw_name;
                  cpItem.bom_code = product.bom_code;
                  cpItem.cp_shu = product.cp_shu;
                  CPdataArray.value.push(cpItem);
                });

                // 使用 Promise.all 来处理所有请求
                Promise.all(CPdataArray.value.map(data => {
                  return axios.put('/api/Scdd_Cp/UpdateScdd_Cp', data)
                    .then(res => {
                      // 可以在这里处理每个请求成功后的逻辑
                    })
                    .catch(error => {
                      console.error(`修改数据失败，错误信息：`, error);
                      // 可以选择抛出错误或返回特定值，以便在 Promise.all 的 .catch 中处理
                      return Promise.reject(error);
                    });
                }))
                  .then(() => {
                    ElMessage.success('修改成功');
                    dialogVisibles.value = false; // 关闭对话框
                    fetchData();
                  })
                  .catch(error => {
                    ElMessage.error('批量修改失败：' + error.message);
                  });
              })
              .catch(error => {
                ElMessage.error('修改失败：' + error.message);
              });
          } else {

            // 新增操作
            axios.post('/api/Mes_SCDD/AddMes_SCDD', formData.value)
              .then(response => {
                productDetailsData.value.forEach(product => {
                  const cpItem = { ...CPdataTemplate.value };
                  cpItem.id = 0;
                  cpItem.scdd_code = formData.value.scdd_code;
                  cpItem.cp_code = product.cp_code;
                  cpItem.cp_name = product.cp_name;
                  cpItem.cp_xh = product.cp_xh;
                  cpItem.cp_lx = product.cp_lx;
                  cpItem.cp_fl = product.cp_fl;
                  cpItem.pp_code = product.pp_code;
                  cpItem.dw_code = product.dw_code;
                  cpItem.dw_name = product.dw_name;
                  cpItem.bom_code = product.bom_code;
                  cpItem.cp_shu = product.cp_shu;
                  CPdataArray.value.push(cpItem);
                });
                for (const data of CPdataArray.value) {
                  try {
                    const response = axios.post('/api/Scdd_Cp/AddScdd_Cp', data);
                    console.log(`新增数据成功，响应信息：`, response.data);
                  } catch (error) {
                    console.error(`新增数据失败，错误信息：`, error);
                  }
                }
                ElMessage.success('新增成功');
                dialogVisibles.value = false; // 关闭对话框
                fetchData();
              })
              .catch(error => {
                ElMessage.error('新增失败：' + error.message);
              });
          }
        } else {
          // 表单验证失败，提示用户
          ElMessage.error('表单验证失败，请检查输入');
        }
      });
    };
    const scddSlComputed = computed(() => {
      return productDetailsData.value.reduce((sum, product) => {
        const quantity = parseInt(product.cp_shu) || 0;
        return sum + quantity;
      }, 0);
    });
    // 处理输入变化
    const handleInputChange = (row) => {
      // 确保输入的是有效的数字
      row.cp_shu = parseInt(row.cp_shu) || 0;
    };

    // 新建操作
    const openDialog = async (row) => {
      Mtkname.value = row ? '编辑生产订单' : '新增生产订单';
      if (row) {
        if (row.scdd_zt == 43) {
          ElMessage.error('该订单已经下发禁止编辑');
        } else {
          Object.assign(formData.value, row);
          const productDetails = await request(`/api/Scdd_Cp/GetScdd_Cp?scdd_code=${row.scdd_code}`);
          productDetailsData.value = productDetails;
          cp_code.value = productDetailsData.value.map(item => item.cp_code);
          dialogVisibles.value = true;
        }
      } else {
        // ;
        Object.assign(formData.value, {
          scdd_code: generateScDDCode(),
          ht_code: generateHTCode(),
        });
        dialogVisibles.value = true;
      }
    };

    // 分页处理
    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    // 监听表格数据变化，更新字典名称
    watchEffect(() => {
      const idsToFetch = new Set();
      filteredTableData.value.forEach((row) => {
        if (row.scdd_xz) idsToFetch.add(row.scdd_xz);
        if (row.scdd_zt) idsToFetch.add(row.scdd_zt);
        if (row.scdd_yxj) idsToFetch.add(row.scdd_yxj);
        if (row.scdd_lx) idsToFetch.add(row.scdd_lx);
      });

      idsToFetch.forEach(async (id) => {
        await getDictionaryName(id, dictionaryNames, request);
      });
    });

    // 显示订单详情对话框
    const Details = async (row) => {
      formData.value = { ...row };
      try {
        const productDetails = await request(`/api/Scdd_Cp/GetScdd_Cp?scdd_code=${row.scdd_code}`);
        productDetailsData.value = productDetails;
      } catch (error) {
        console.error('Error fetching product details:', error);
      }
      dialogVisible.value = true;
    };
    //生成生产计划code
    function generateScjhCode() {
      const prefix = 'SCJH';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    //生成生产订单code
    function generateScDDCode() {
      const prefix = 'SCDD';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    //生成合同code
    function generateHTCode() {
      const prefix = 'HT';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    // 下发操作
    const Issue = async (row) => {
      // 确认下发  
      try {
        await ElMessageBox.confirm('确定下发吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const productDetails = await request(`/api/Scdd_Cp/GetScdd_Cp?scdd_code=${row.scdd_code}`);
        productDetailsData.value = productDetails;

        if (row.scdd_zt !== 43) {
          // 循环发送每个产品详情数据到后端  
          await Promise.all(productDetailsData.value.map(async (product, i) => {
            const scjhCode = generateScjhCode();
            await axios.post('/api/Mes_scjh/AddMesScjh', {
              scjh_id: 0,
              scjh_state: 56,
              scjh_yxj: parseInt(row.scdd_yxj),
              scjh_jd: 0,
              scjh_code: scjhCode,
              scjh_lx: parseInt(row.scdd_lx),
              scjh_xz: parseInt(row.scdd_xz),
              ks_code: row.ks_code,
              ks_name: row.ks_name,
              ht_code: row.ht_code,
              scjh_gdsl: 0,
              cp_name: product.cp_name,
              cp_code: product.cp_code,
              cp_xh: product.cp_xh,
              cp_lx: parseInt(product.cp_lx),
              cp_fl: parseInt(product.cp_fl),
              pp_code: product.pp_code,
              dw_code: product.dw_code,
              dw_name: product.dw_name,
              bom_code: product.bom_code,
              scjh_sl: parseInt(product.cp_shu),
              scjh_yscsl: 0,
              scjh_kssj: new Date(row.planned_start_time),
              scjh_jssj: new Date(row.planned_completion_time),
              scjh_xqrq: new Date(row.delivery_date),
              scjh_bz: row.seddbz,
              scjh_fjzt: 0,
              scdd_code: row.scdd_code,
              create_by: sessionStorage.getItem('u'),
              create_time: new Date(),
              update_by: 1,
              update_time: new Date()
            });
            console.log(`第 ${i + 1} 条产品详情下发成功`);
          }));

          // 更新状态  
          const url = `/api/Mes_SCDD/UpdateStatus?code=${row.scdd_code}&state=43&update_by=${sessionStorage.getItem('u')}`;
          await axios.put(url, {});

          ElMessage.success('所有产品详情下发成功');
          fetchData();
        } else {
          ElMessage.error('产品已下发');
        }
      } catch (error) {
        if (error.response) {
          ElMessage.error('下发失败: ' + error.response.data.message);
        } else {
          ElMessage({
            type: 'info',
            message: '已取消下发'
          });
        }
      }
    };
    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
      dialogVisibles.value = false;
      formData.value = {
        scdd_code: '',
        scdd_yxj: null,
        scdd_lx: null,
        scdd_xz: null,
        ks_code: '',
        ht_code: '',
        cp_code: '',
        scdd_sl: '',
        delivery_date: null,
        planned_start_time: null,
        planned_completion_time: null,
        seddbz: ''
      };
      productDetailsData.value = [];
    };
    //显示产品模态框
    const toggleCPMTK = () => {
      isCPMTKVisible.value = !isCPMTKVisible.value; // 切换显示状态  
    };

    //显示客商模态框
    const toggleKsMTK = () => {
      isKsMTKVisible.value = !isCPMTKVisible.value; // 切换显示状态  
    };
    // 选择产品  
    const handleSelectionConfirmed = async (ids) => {
      cp_code.value = ids;
      productDetailsData.value = []; // 初始化为一个空数组  

      try {
        // 创建请求数组  
        const requests = ids.map(cp_code => {
          return axios.get(`/api/BD_CP/GetBD_CPcp_code?cp_code=${cp_code}`);
        });

        // 等待所有请求完成  
        const responses = await Promise.all(requests);

        // 将所有获取到的产品数据添加到 productDetailsData 中  
        responses.forEach(response => {
          productDetailsData.value.push(response.data); // 假设 response.data 是单个产品数据  
        });
      } catch (error) {
        console.error('获取产品详情失败:', error);
        ElMessage.error('加载产品详情失败，请稍后再试');
      } finally {
        isCPMTKVisible.value = false; // 在所有请求完成后关闭对话框  
      }
    };

    //关闭产品模态框
    const handleCancelSelection = () => {
      isCPMTKVisible.value = false;
    };
    //选择客商
    const handleSelectionConfirmeds = (data) => {
      formData.value.ks_code = data.id;
      formData.value.ks_name = data.name;
      isKsMTKVisible.value = false;
    };
    //关闭客商模态框
    const handleCancelSelections = () => {
      isKsMTKVisible.value = false;
    };
    // 初始化数据
    fetchData();
    watch(scddSlComputed, (newValue) => {
      formData.value.scdd_sl = newValue; // 更新 formData 的 scdd_sl  
    });
    return {
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      filteredTableData,
      openDialog,
      handleCurrentChange,
      formatDate,
      dictionaryNames,
      dialogVisible,
      formData,
      productDetailsData,
      formRules,
      formRef,
      Details,
      Issue,
      closeDialog,
      dialogVisibles,
      generateScDDCode,
      Mtkname,
      toggleCPMTK,
      isCPMTKVisible,
      isKsMTKVisible,
      toggleKsMTK,
      priorityOptions,
      orderTypeOptions,
      handleSelectionConfirmed,
      handleCancelSelection,
      handleSelectionConfirmeds,
      handleCancelSelections,
      generateHTCode,
      saveForm,
      handleInputChange,
      ddsz,
      cp_code,
      CPdataTemplate,
      CPdataArray,
      Withdraw,
      End,
      scddSlComputed
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
  background-color: rgba(255, 255, 255, 0);
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 15px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #409eff;
  border-radius: 15px 0 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgb(0, 0, 0);
  font-weight: bold;
  transition: width 0.3s;
}

.order-dialog {
  border-radius: 30px;
  width: 30%;
}
.order-dialog .el-dialog__header {
  background-color: #f0f2f5;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px 20px;
}

.order-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.order-dialog .el-dialog__body {
  padding: 20px;
}

.order-dialog .el-form-item {
  margin-bottom: 15px;
}

.order-dialog .el-form-item__label {
  font-weight: bold;
  color: #606266;
}

.product-title {
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 10px;
}

.product-table {
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
}

.progress-bar {
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #409eff;
  color: white;
  text-align: center;
  line-height: 20px;
  border-radius: 4px;
}
</style>